package httpx

import (
	"fmt"
	"gitee.com/whilew/cream/pkg/basic_component/conf"
	"gitee.com/whilew/cream/pkg/util/xerror"
	"github.com/gin-gonic/gin"
	"net/http"
	"reflect"
)

type Response struct {
	Code  int         `json:"code"`
	Data  interface{} `json:"data"`
	Msg   interface{} `json:"msg"`
	ReqId string      `json:"req_id"`
}

const (
	SUCCESS = 0

	ERROR   = 500 // 服务器内部逻辑异常
	DBERROR = 501 // 数据库处理异常
	NoFind  = 404
)

func Result(c *gin.Context, ResCode int, ResMsg interface{}, ResData interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:  ResCode,
		Msg:   ResMsg,
		Data:  ResData,
		ReqId: GetReqId(c),
	})
	c.Abort()
}

func NoFindResult(c *gin.Context) {
	c.Status(http.StatusNotFound)
	c.Abort()
}

func Ok(c *gin.Context) {
	Result(c, SUCCESS, "操作成功", nil)
}
func OkWithMessage(c *gin.Context, ResMsg interface{}) {
	Result(c, SUCCESS, ResMsg, nil)
}
func OkWithData(c *gin.Context, ResData interface{}) {
	Result(c, SUCCESS, "操作成功", ResData)
}
func OkDetailed(c *gin.Context, ResMsg interface{}, ResData interface{}) {
	Result(c, SUCCESS, ResMsg, ResData)
}

func Fail(c *gin.Context) {
	Result(c, ERROR, "系统异常，请稍后重试", nil)
}
func FailWithMessage(c *gin.Context, ResMsg interface{}) {
	Result(c, ERROR, ResMsg, nil)
}
func FailWithData(c *gin.Context, ResData interface{}) {
	Result(c, ERROR, "系统异常，请稍后重试", ResData)
}
func FailWithDetailed(c *gin.Context, ResCode int, ResMsg interface{}, ResData interface{}) {
	Result(c, ResCode, ResMsg, ResData)
}
func FailWithError(c *gin.Context, err error) {
	GetLoger(c).Error(fmt.Sprintf("[ERROR] (%s) %s", reflect.TypeOf(err).String(), err.Error()))
	switch err.(type) {
	case *xerror.BusinessError:
		Result(c, 500, err.Error(), err.(*xerror.BusinessError).Codes)
	case *xerror.Dberror:
		if conf.GetApplicationEnv() != "release" {
			Result(c, 500, "数据库异常，请稍后重试["+err.Error()+"]", nil)
		} else {
			Result(c, 500, "数据库异常，请稍后重试", nil)
		}
	default:
		Result(c, 500, err.Error(), nil)
	}
}
func FailWithDbError(c *gin.Context, err error) {
	GetLoger(c).WithModule("db").Error("[ERROR] 数据库处理异常" + err.Error())
	Result(c, DBERROR, "数据库异常，请稍后重试", nil)
}
